import urllib.request
import urllib.parse
import json

class RegUse:
    """用户注册许可"""
    def __init__(self, arg):
        self.crtFilePath = arg["path"]
        self.permAPI = arg["url"]
    # 写入本地许可文件（加密）
    def wPerm(self,regInf):
        '''
        regIf = {'key':秘钥 ,times:次数,timer:时间戳（13位）}
        '''
        # 组织数据，写入许可文件
        res = (int(regInf['times']) + int(regInf['timer'])) ^ int(regInf['key'])
        regStr = "===Permission===\n"
        regStr += str(regInf['key']) + '\n'
        regStr += str(res) + '\n'
        regStr += str(regInf['timer']) + '\n' 
        regStr += str(res + int(regInf['key'])) + '\n'
        regStr += str(res + int(regInf['timer'])) + '\n'
        with open(self.crtFilePath,"w") as fp:
            fp.write(regStr)
    # 读本地的许可文件（解密）
    def rPerm(self):
        '''
        返回一个字典 
        {"isOk":状态,"error":错误信息,"data":正常数据}
        '''
        data={}
        try:
            with open(self.crtFilePath,'r') as fp:
                res = fp.readlines()
        except:
            resTable = {"isOk":False,"error":"File Except"}
            return resTable
        # 排除内容异常
        resTable = {"isOk":False,"error":"Content Except"}
        if len(res) != 6:
            return resTable
        if int(res[4]) != int(res[1])+int(res[2]):
            return resTable 
        if int(res[5]) != int(res[2])+int(res[3]):
            return resTable
        # 读取正常数据
        resTable = {'isOk': True,"data":data}
        data["key"] = int(res[1])
        data["timer"] = int(res[3])
        data["times"] = (int(res[1]) ^ int(res[2])) - int(res[3])
        return resTable

    # 检查本地许可(运行一次，本地许可次数减一)
    def checkPerm(self):
        res = self.rPerm()
        if res["isOk"] == False:
            return False
        if res['data']['times'] > 0:
            res['data']['times'] -= 1
            self.wPerm(res['data'])
            return res['data']['times']
    # 链接服务器
    def linkAPI(self,linkData):
        '''
        linkData = {'headers' : {}, 'values' : {} }
        '''
        # 默认headers
        headers = {'User-Agent': 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'};
        if 'headers' in linkData :
            headers = linkData['headers']
        # 将字典格式化成能用的形式
        data = urllib.parse.urlencode(linkData['values']).encode('utf-8')
        # 创建一个request,放入我们的地址、数据、头
        request = urllib.request.Request(self.permAPI, data, headers)
        try:
            html = urllib.request.urlopen(request).read().decode('utf-8')
        except :
            return False
        return json.loads(html)

    # 验证程序许可
    def userLimited(self,linkData):
        '''
        先post数据到服务器查询,得到服务器的许可，则将permission文件填入10次
        未得到服务器的许可则查询permission文件中是否还有次数，
        返回次数
        permission文件简单异或加密处理
        '''
        # 此处应该做个异步操作，链接API比较费时间
        res = self.linkAPI(linkData)

        if res != False:
            regInf = {
                'key' : res['userId'],
                'times' : res['t'],
                'timer' : res['timer']
            }
            self.wPerm(regInf)
            prem = res['t']
        else :
            prem = self.checkPerm()
        return prem
if __name__ == '__main__':

    linkData ={
        'values' : {
            'userId'   : '1312308948',
            'userName' : '欧皓辰',
            'title'    : '如何不被车撞倒'
        }
    }
    # 初始化检查对象
    ckPerm = RegUse({"path":"./RegUse_data.ctx","url":"http://127.0.0.1:8080/LWAPI"})
    # 检查
    res = ckPerm.userLimited(linkData)
    # 返回使用次数
    print(res)